<template>
  <div class="search">
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search
        v-model="userKey"
        placeholder="请输入搜索关键词"
        shape="round"
      >
      </van-search>
      <div @click="onSearch">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <span
        v-for="(item, index) in history"
        :key="index"
        @click="Search(item)"
        >{{ item }}</span
      >
    </div>
    <div class="historyList">
      <h2>搜索结果</h2>
      <router-link
        :to="'/articleDetail/' + item.id"
        v-for="item in searchdata"
        :key="item.id"
        >{{ item.title }}</router-link
      >
    </div>
  </div>
</template>

<script>
// 搜索
import { search } from "@/apis/post.js";
export default {
  data() {
    return {
      userKey: "",
      searchdata: [],
      history: [], //搜索历史记录
    };
  },
  activated() {
    // localStorage.setItem('historyData',this.history)
    let history = localStorage.getItem("historyData");
    // console.log(history);
    // 判断是否有本地记录
    if (history) {
      this.history = JSON.parse(history);
    }
  },
  methods: {
    // 搜索文章
    async onSearch() {
      // 发出请求
      let res = await search(this.userKey);
      // console.log(res);
      this.searchdata = res.data.data;
      // console.log(this.searchdata);

      // 如果搜索记录是重复的话就删除数组有的记录再加入数组
      let index = this.history.indexOf(this.userKey);
      if (index !== -1) this.history.splice(index, 1); // 干掉数组里重复的

      // 把历史记录存进本地储存
      this.history.unshift(this.userKey);
      // 最多保留10个历史记录
      // console.log(this.history.length);
      if (this.history.length > 9)
        this.history.splice(this.history.length - 1, 1);
      // console.log(typeof this.history);
      localStorage.setItem("historyData", JSON.stringify(this.history));
    },
    // 历史记录点击
    Search(item) {
      this.userKey = item;
      this.onSearch();
    },
  },
};
</script>

<style lang='less' scoped>
.header {
  display: flex;
  height: 50px;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  border-bottom: 1px solid #ccc;
  .van-search {
    flex: 1;
    padding: 5px 12px;
  }
}
.historyList {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  span {
    padding: 5px;
    height: 30px;
    line-height: 30px;
    border: 1px solid #ccc;
    margin-right: 5px;
    border-radius: 5px;
  }
  h2 {
    line-height: 40px;
    font-weight: bold;
  }
  > a {
    display: block;
    text-decoration: underline;
    line-height: 30px;
    color: #666;
  }
}
</style>